package com.desk.api.controller;

import com.desk.api.emtity.ControlDto;
import com.desk.api.emtity.DeskConfig;
import com.desk.api.emtity.Result;
import com.desk.api.mqtt.MqttPublishServer;
import com.desk.api.service.DeskConfigService;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/desk/config")
public class DeskConfigController {

  @Resource private DeskConfigService deskConfigService;
  @Resource MqttPublishServer mqttPublishServer;

  @Value("${smartDesk.config-report}")
  private String configReportTopic;

  @Value("${smartDesk.control}")
  private String controlTopic;

  @Schema(description = "获取最新配置")
  @GetMapping("/getLastConfig")
  public Result<DeskConfig> getLastConfig() {
    DeskConfig config =
        deskConfigService
            .lambdaQuery()
            .orderByDesc(DeskConfig::getCreateTime)
            .last("limit 1")
            .one();
    return Result.success(config);
  }

  @Schema(description = "更新配置")
  @PostMapping("/updateConfig")
  public Result saveConfig(@RequestBody DeskConfig config) {
    deskConfigService.save(config);
    mqttPublishServer.publish(config.getContent(), configReportTopic);
    return Result.success();
  }

  @Schema(description = "远程控制")
  @PostMapping("control")
  public Result control(@RequestParam ControlDto content) {
    mqttPublishServer.publish(content, controlTopic);
    return Result.success();
  }
}
